package com.tl.sun.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTabHost;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.utils.FileUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.orhanobut.logger.Logger;
import com.proxy.sosdk.SoProxy;
import com.tl.sun.AppConfig;
import com.tl.sun.AppContext;
import com.tl.sun.OkHeader;
import com.tl.sun.R;
import com.tl.sun.event.ExpireRemind;
import com.tl.sun.event.MainEvent;
import com.tl.sun.helper.UIHelper;
import com.tl.sun.manager.MDAccountMgr;
import com.tl.sun.manager.MDUserMgr;
import com.tl.sun.manager.RobustVersionManager;
import com.tl.sun.model.RobustBean;
import com.tl.sun.robust.HotFixPresenter;
import com.tl.sun.robust.JudgeIfHotFix;
import com.tl.sun.service.BeatService;
import com.tl.sun.ui.dialog.ExpireDialog;
import com.tl.sun.ui.fragment.ComboFragment;
import com.tl.sun.ui.fragment.HelperFragment;
import com.tl.sun.ui.fragment.HomeFragment;
import com.tl.sun.ui.fragment.MeFragment;
import com.tl.sun.utils.AESHelper;
import com.tl.sun.utils.StatisticsUtil;
import com.tl.sun.utils.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import me.leolin.shortcutbadger.ShortcutBadger;
import okhttp3.Call;
import okhttp3.Response;


public class MainActivity extends BaseActivity implements JudgeIfHotFix {

    private FragmentTabHost mTabHost;
    private LayoutInflater layoutInflater;
    private TextView tabTv;
    private StatisticsUtil mStatistUtil;
//    private List<String> test = new ArrayList<>();

    private static final String COUNT_INSTALL_TYPE = "1";

    private static final String COUNT_START_TYPE = "2";

    private WebView webview;

    private int mImageViewArray[] = {R.drawable.main_tab_homes, R.drawable.main_tab_pays, R.drawable.main_tab_helpes, R.drawable.main_tab_mes};
    private final Class fragmentArray[] = {HomeFragment.class, ComboFragment.class, HelperFragment.class, MeFragment.class};

    private String mTextviewArray[] = {"更换IP", "购买", "帮助", "个人中心"};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //  EventBus.getDefault().register(this);
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        layoutInflater = LayoutInflater.from(this);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.contentPanel);

        int fragmentCount = fragmentArray.length;
        for (int i = 0; i < fragmentCount; i++) {
            //为每一个Tab按钮设置图标、文字和内容
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
            //将Tab按钮添加进Tab选项卡中
            mTabHost.addTab(tabSpec, fragmentArray[i], null);
            mTabHost.getTabWidget().setDividerDrawable(null);
        }
        mTabHost.setCurrentTab(0);
//        for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
//            if (mTabHost.getCurrentTab() == i) {
//                tabTv.setTextColor(this.getResources().getColor(R.color.me_btn_color));
//            } else {
//                tabTv.setTextColor(this.getResources().getColor(R.color.white));
//            }
//        }
//        mTabHost.getTabWidget().getChildTabViewAt(1).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(MainActivityV2.this, PublishLiveActivity.class));
//
//            }
//        });
        mStatistUtil = new StatisticsUtil(this);
        //清除桌面 logo角标
        SharedPreferences countSp = getSharedPreferences("count", Context.MODE_PRIVATE);
        countSp.edit().clear().apply();
        ShortcutBadger.removeCount(this);


        if (MDUserMgr.getInstance().getThreeDayExpire()) {//如果快过期
            String coupoum = MDUserMgr.getInstance().getCoupoum();
            if (!TextUtils.isEmpty(coupoum)) {
                ExpireDialog expireDialog = ExpireDialog.newInstance(coupoum);
                expireDialog.show(getSupportFragmentManager().beginTransaction(), "");
            }
        }

        new HotFixPresenter(this).getHotFixMessage(this);
        MDAccountMgr.getInstance().getCache(AppContext.getInstance());
        if (AppConfig.getInstance().getHasLauch()) {
            count(COUNT_INSTALL_TYPE);
        }
        count(COUNT_START_TYPE);
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(ExpireRemind event) {
        if (event.isExpire()) {
            String coupoum = MDUserMgr.getInstance().getCoupoum();
            ExpireDialog expireDialog = ExpireDialog.newInstance(coupoum);
            expireDialog.show(getSupportFragmentManager().beginTransaction(), "");
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(MainEvent event) {
        mTabHost.setCurrentTab(1);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //    EventBus.getDefault().unregister(this);
    }


    private View getTabItemView(int index) {
        View view = layoutInflater.inflate(R.layout.tab_content, null);
        ImageView icon = (ImageView) view.findViewById(R.id.tab_icon);
        tabTv = (TextView) view.findViewById(R.id.tab_tv);
        icon.setImageResource(mImageViewArray[index]);
        tabTv.setText(mTextviewArray[index]);
        return view;
    }


    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            //两秒之内按返回键就会退出
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.showToast("");
                Toast.makeText(MainActivity.this, getResources().getString(R.string.tips_exit_out), Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                SoProxy.getInstance().stopProxy();
                finish();
                System.exit(0);
            }

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onSuccess(RobustBean.RetDataBean data, String msg) {
        final int vCode = data.getvCode();
        final String vName = data.getvName();
        String url = data.getUrl();
        if (vCode > RobustVersionManager.getInstance().getvCode()) {
            OkGo.get(url)
                    .execute(new FileCallback(Environment.getExternalStorageDirectory().getPath() + File.separator + "robust", "patch.jar") {
                        @Override
                        public void onSuccess(File file, Call call, Response response) {
                            //解密
                            AESHelper.decryptFile("abcdefghabcdefgh", Environment.getExternalStorageDirectory().getPath() + File.separator + "robust/patch.jar"
                                    , Environment.getExternalStorageDirectory().getPath() + File.separator + "robust1/patch.jar");
                            //解密之后清除掉 robust 文件夹
                            FileUtils.deleteDir(Environment.getExternalStorageDirectory().getPath() + File.separator + "robust");
                            //移动
                            FileUtils.copyFile(Environment.getExternalStorageDirectory().getPath() + File.separator + "robust1/patch.jar",
                                    Environment.getExternalStorageDirectory().getPath() + File.separator + "robust/patch.jar");

                            //删除
                            FileUtils.deleteDir(Environment.getExternalStorageDirectory().getPath() + File.separator + "robust1");
                            UIHelper.loadPatch(true, vCode, vName);
                        }
                    });
        }
    }

    @Override
    public void onError(String msg) {

    }

    private void count(String type) {
        HashMap<String, String> map = new HashMap<>();
        map.put("client_num", mStatistUtil.getDeviceUuid().toString());
        map.put("type", type);
        JSONObject jsonObject = new JSONObject(map);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHead(AppContext.getInstance())).post(AppContext.getInstance().getBaseUrl() + "client/app_log")
                .tag(this)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                             @Override
                             public void onSuccess(String s, Call call, Response response) {

                             }

                             @Override
                             public void onError(Call call, Response response, Exception e) {

                             }
                         }

                );
    }
}
